#include "teammembermodel.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlRecord>

teamMemberModel::teamMemberModel(QSqlDatabase db, QObject *parent) :
    QStandardItemModel(0, 5, parent),
    dbase(db),
    modelMember(new QSqlTableModel(this, dbase)),
    modelTeam(new QSqlTableModel(this, dbase)),
    modelTeamMember(new QSqlRelationalTableModel(this, dbase)),
    col_id_teamMember(-1),
    col_team_teamMember(-1),
    col_member_teamMember(-1),
    col_id_team(-1),
    col_title_team(-1),
    col_organization_team(-1),
    col_id_member(-1),
    col_name_member(-1)
{
    setHeaderData(col_team_or_member_view, Qt::Horizontal, tr("team") + "/" + tr("member"));
    setHeaderData(col_id_view, Qt::Horizontal, tr("id"));
    setHeaderData(col_organization_view, Qt::Horizontal, tr("oranization"));
    setHeaderData(col_change_view, Qt::Horizontal, tr("Changed"));
    setHeaderData(col_member_view, Qt::Horizontal, tr("member id"));

    modelTeam->setEditStrategy(QSqlTableModel::OnManualSubmit);
    modelTeamMember->setEditStrategy(QSqlTableModel::OnManualSubmit);
    modelMember->setEditStrategy(QSqlTableModel::OnManualSubmit);

    select();
}
bool teamMemberModel::submit()
{
    return false;
}

bool teamMemberModel::submitManual()
{
    for (int teamid = 0; teamid < modelTeam->rowCount(); ++teamid) {
        qDebug() << tr("Record") + " " + modelTeam->data(modelTeam->index(teamid, 0)).toInt() <<
                    " " + modelTeam->data(modelTeam->index(teamid, 1)).toString() <<
                    " " + modelTeam->data(modelTeam->index(teamid, 2)).toString();
    }
    if (modelTeam->submit() ) {

        /// @todo submit team-member
        if (modelTeamMember->submit ()) {

        } else {
            QMessageBox::warning (0, tr("Team data submit error"), tr("I can`t submit team member data to base."),
                                  QMessageBox::Close, QMessageBox::Close);
        }
    } else {
        QMessageBox::warning (0, tr("Team data submit error"), tr("I can`t submit team data to base."),
                              QMessageBox::Close, QMessageBox::Close);
    }
    for (int teamid = 0; teamid < modelTeam->rowCount(); ++teamid) {
        qDebug() << tr("Record") + " " + modelTeam->data(modelTeam->index(teamid, 0)).toInt() <<
                    " " + modelTeam->data(modelTeam->index(teamid, 1)).toString() <<
                    " " + modelTeam->data(modelTeam->index(teamid, 2)).toString();
    }
    return false;
}

void teamMemberModel::revert()
{
    select();
}

bool teamMemberModel::select()
{
    bool retCode;
    modelMember->setTable ("member");
    modelTeam->setTable ("team");
    modelTeamMember->setTable ("team_member");

    for (int id = 0; id < modelTeamMember->columnCount(); id++) {
        if (modelTeamMember->headerData(id,Qt::Horizontal) == "id") col_id_teamMember = id;
        if (modelTeamMember->headerData(id,Qt::Horizontal) == "team") col_team_teamMember = id;
        if (modelTeamMember->headerData(id,Qt::Horizontal) == "member") col_member_teamMember = id;
    }
    for (int id = 0; id < modelTeam->columnCount(); id++) {
        if (modelTeam->headerData(id,Qt::Horizontal) == "id") col_id_team = id;
        if (modelTeam->headerData(id,Qt::Horizontal) == "title") col_title_team = id;
        if (modelTeam->headerData(id,Qt::Horizontal) == "organization") col_organization_team = id;
    }
    for (int id = 0; id < modelMember->columnCount(); id++) {
        if (modelMember->headerData(id,Qt::Horizontal) == "id") col_id_member = id;
        if (modelMember->headerData(id,Qt::Horizontal) == "name") col_name_member = id;
    }

    disconnect (this, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setChageFlag(QModelIndex,QModelIndex)));
    removeRows(0, rowCount());
    retCode = modelMember->select ();
    retCode = retCode && modelTeam->select ();
    retCode = retCode && modelTeamMember->select ();

    for (int row = 0; row < modelTeam->rowCount (); row++) {
        insertRow (row, false);
        setData (index (row, col_team_or_member_view), modelTeam->data (modelTeam->index (row, col_title_team)).toString ());
        setData (index (row, col_id_view), modelTeam->data (modelTeam->index (row, col_id_team)).toString ());
        setData (index (row, col_organization_view), modelTeam->data (modelTeam->index (row, col_organization_team)).toString ());
        setItem (row, col_change_view, new QStandardItem(" "));
        if (!index(row, col_team_or_member_view).parent().isValid()) {
            for (int teamMember = 0; teamMember < modelTeamMember->rowCount(); teamMember++) {
                if (modelTeamMember->data(modelTeamMember->index(teamMember, col_team_teamMember)).toInt() == data(index(row, col_id_view)).toInt()) {
                    QString memberName;
                    for (int member = 0; member < modelMember->rowCount(); ++member) {
                        if (modelMember->data(modelMember->index(member, col_id_member)).toInt() == modelTeamMember->data(modelTeamMember->index(teamMember, col_member_teamMember)).toInt())
                            memberName = modelMember->data(modelMember->index(member, col_name_member)).toString();
                    }

                    addChild(index(row, col_team_or_member_view)
                             , memberName
                             , modelTeamMember->data(modelTeamMember->index(teamMember, col_member_teamMember)).toInt()
                             , false
                             , modelTeamMember->data(modelTeamMember->index(teamMember, col_id_teamMember)).toInt());
                }
            }
        }
    }

    connect (this, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(setChageFlag(QModelIndex,QModelIndex)));
    return retCode;
}

void teamMemberModel::addChild(QModelIndex root_index, QString name, int childId, bool isManualAdd, int team_member_id)
{
    QString chFlag = isManualAdd ? "*" : " ";
    bool igenderists = false;
    if (root_index.parent().isValid()) root_index = root_index.parent();
    int row = item(root_index.row())->rowCount();
    disconnect (this, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setChageFlag(QModelIndex,QModelIndex)));
    for (int id = 0; id != item(root_index.row())->rowCount(); id++)
    {
        if (childId == item(root_index.row())->child(id, col_member_view)->data(Qt::DisplayRole).toInt()) {
            igenderists = true;
        }
    }
    if (!igenderists) {
        item(root_index.row())->setChild(row, new QStandardItem(name));
        item(root_index.row())->child(row)->setEditable(false);
        item(root_index.row())->setChild(row, col_organization_view, new QStandardItem(""));
        item(root_index.row())->child(row, col_organization_view)->setEditable(false);
        item(root_index.row())->setChild(row, col_change_view, new QStandardItem(chFlag));
        item(root_index.row())->child(row, col_change_view)->setEditable(false);
        item(root_index.row())->setChild(row, col_member_view, new QStandardItem(QString::number(childId)));
        if (isManualAdd) {
            for (int tm = 0; tm < modelTeamMember->rowCount(); tm++) {
                if (team_member_id <= modelTeamMember->data(modelTeamMember->index(tm, col_id_teamMember)).toInt())
                    team_member_id = modelTeamMember->data(modelTeamMember->index(tm, col_id_teamMember)).toInt()+1;
            }
        }
        item(root_index.row())->setChild(row, 1, new QStandardItem(QString::number(team_member_id)));
        if (isManualAdd) {
            int mt_row = modelTeamMember->rowCount ();
            modelTeamMember->insertRow (mt_row);
            modelTeamMember->setData (modelTeamMember->index (mt_row, col_id_teamMember), team_member_id);
            modelTeamMember->setData (modelTeamMember->index (mt_row, col_member_teamMember), childId);
            /// @bug Incorrect value from current team id
            modelTeamMember->setData (modelTeamMember->index (mt_row, col_team_teamMember), data (index (row, col_id_view)).toInt ());
            qDebug() << tr("Current team ") << data (index (row, col_id_view)).toInt () << root_index;
        }
    }
    connect (this, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(setChageFlag(QModelIndex,QModelIndex)));
}

void teamMemberModel::dropChild(QModelIndex deleted_index)
{
    if (deleted_index.parent().isValid()) {
        if (QMessageBox::question(0 , tr("Member base") ,
                                  tr("Exclude member ") + data(deleted_index).toString() + tr(" from team ") + data(deleted_index.parent()).toString() + "?",
                                  QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) {
            item(deleted_index.parent().row())->child(deleted_index.row(), col_change_view)->setData("!", Qt::DisplayRole);
            for (int id = 0; id < modelTeamMember->rowCount (); id++) {
                if (modelTeamMember->data (modelTeamMember->index (id, col_id_teamMember)).toInt () == item (deleted_index.parent ().row ())->child (deleted_index.row (), col_id_view)->data (Qt::DisplayRole).toInt ()) modelTeamMember->removeRow (id);
            }
        }
    }
}

bool teamMemberModel::insertRow(int row, bool isManualSubmit, const QModelIndex &parent)
{
    bool retcode = QAbstractItemModel::insertRow(row, parent);
    if (retcode) {
        int teamId = 1;
        for (int id = 0; id<rowCount(); id++) {
            if (teamId <= data(index(id, col_id_view)).toInt()) teamId = data(index(id, col_id_view)).toInt() + 1;
        }
        setData(index(row, col_id_view), teamId, Qt::EditRole);
        setData(index(row, col_team_or_member_view),tr("Team No ") + QString::number(teamId), Qt::EditRole);
        setData(index(row, col_organization_view),tr("Organization No ") + QString::number(teamId), Qt::EditRole);
        setItem (row, col_change_view, new QStandardItem("*"));
        item (row, col_change_view)->setEditable (false);
    }
    if (isManualSubmit) {
        int mt_row = modelTeam->rowCount();
        modelTeam->insertRow (mt_row);
        modelTeam->setData (modelTeam->index (mt_row, col_id_team), data (index (row, col_id_view)).toInt ());
        modelTeam->setData (modelTeam->index (mt_row, col_title_team), data (index (row, col_team_or_member_view)).toString());
        modelTeam->setData (modelTeam->index (mt_row, col_organization_team), data (index (row, col_organization_view)).toString());
    }
    return retcode;
}

void teamMemberModel::setChageFlag (QModelIndex topLeft, QModelIndex botRight)
{
    /** @fn setChageFlag
     * @brief set flag of record change
     *
     * @param topLeft top left field of changed area
     * @param botRight bottom right field of changed area
     */

    int row = botRight.row();

    disconnect (this, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setChageFlag(QModelIndex,QModelIndex)));

    if (topLeft.isValid () && botRight.isValid ()) {
        qDebug() << "change area" << topLeft.column() << botRight.column();
        if ((data(index(row, col_change_view)).toString() != "!") &&
                (topLeft.column () == col_team_or_member_view || topLeft.column () == col_organization_view)) {
            setData (index (botRight.row (), col_change_view), "*");

            //            for (int trow = 0; trow < modelTeam->rowCount(); trow++) {
            //                if (data(index(row, col_id_view)).toInt() == modelTeam->data(index(trow, col_id_team)).toInt()) {
            //                    modelTeam->setData(modelTeam->index(trow, col_title_team), data(index(row, col_team_or_member_view)).toString());
            //                    modelTeam->setData(modelTeam->index(trow, col_organization_team), data(index(row, col_organization_view)).toString());

            //                    qDebug() << "dbase model" << modelTeam->data(modelTeam->index(trow, col_title_team)).toString() << modelTeam->data(modelTeam->index(trow, col_organization_team)).toString();
            //                }
            //            }

            /// \todo find in dbase model
            for (int tm_row = 0; tm_row < modelTeam->rowCount(); ++tm_row) {
                if (modelTeam->record(tm_row).value("id").toInt() == data(index(row, col_id_view)).toInt()) {
                    qDebug() << "record :" << modelTeam->data(modelTeam->index(tm_row, col_id_team)).toInt() <<
                                modelTeam->data(modelTeam->index(tm_row, col_title_team)).toString() << modelTeam->data(modelTeam->index(tm_row, col_organization_team)).toString();
                    qDebug() << "model:" << data(index(row, col_id_view)).toInt() <<
                                data(index(row, col_team_or_member_view)).toString() << data(index(row, col_organization_view)).toString();

                    modelTeam->setData(modelTeam->index(tm_row, col_title_team), data(index(row, col_team_or_member_view)).toString());
                    modelTeam->setData(modelTeam->index(tm_row, col_organization_team), data(index(row, col_organization_view)).toString());
                }
            }
            /// \todo if exists change value in database model
        }
    }
    connect (this, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(setChageFlag(QModelIndex,QModelIndex)));
}

bool teamMemberModel::removeRow(int row, const QModelIndex &parent)
{
    bool retCode = false;
    if (!parent.isValid()) for (int id = 0; id < modelTeam->rowCount(); id++) {
        if (data(index(row, col_id_view)).toInt() == modelTeam->data(modelTeam->index(id, col_id_team)).toInt()) {
            retCode = modelTeam->removeRow(id);
        }
    }
    if (retCode) {
        setItem (row, col_change_view, new QStandardItem("!"));
    }
    else {
        QMessageBox::critical(0, tr("Member base"), tr("I don`t can remove team ") + data(index(row, col_team_or_member_view)).toString(),
                              QMessageBox::Close, QMessageBox::Close);
    }
    return retCode;
}
